const express = require('express'),
    route = express.Router();

route.post('/login', (req, res) => {
    let {name, password} = req.body || {};

    //=>req.personalDATA： Information from previously read PERSONAL（personal.json）
    // Login verification is to find the information passed by the user in the total data, and it means that the login is successful
    const item = req.personalDATA.find(item => {
        //=>Support username transfer: name, email, phone
        return (item.name === name || item.email === name || item.phone === name) && item.password === password;
    });

    if (item) {
        //=>Successful login: Store the ID of the currently logged in user on SESSION
        //(if there is user information on SESSION, it means that the login was successful, otherwise there is no login)
        req.session.personID = parseFloat(item.id);
        res.send({code: 0, msg: 'OK!'})
        return;
    }
    res.send({code: 1, msg: 'NO!'});
});

route.get('/login', (req, res) => {
    //=>Whether to log in depends on the existence of SESSION (the background service restarts, SESSION disappears)
    const personID = req.session.personID;
    if (personID) {
        res.send({code: 0, msg: 'OK!'});
        return;
    }
    res.send({code: 1, msg: 'NO!'});
});

route.get('/info', (req, res) => {
    //=>Get the current login information: Get the login ID from SESSION
    const personID = req.session.personID;
    if (personID) {
        //=>Filter all items with the same login ID
        let personInfo = req.personalDATA.find(item => {
            return parseFloat(item.id) === personID;
        });
        personInfo.password = null;//=> Don't bring your password in the returned information
        res.send({code: 0, msg: 'OK!', data: personInfo});
        return;
    }
    res.send({code: 1, msg: 'NO!', data: null});
});

route.get('/out', (req, res) => {
    //=>Logout is to kill SESSION
    req.session.personID = null;
    res.send({code: 0, msg: 'OK!'});
});

module.exports = route;